<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

final class Admin_Filemanager
{
	/**
	 * Initialization
	 *
	 * @return void
	 */
	public function initialize()
	{
		// initialize main directories
		$this->initDir();

		Admin::header(_ADMIN_FILEMANAGER);

		echo "<h1>"._ADMIN_FILEMANAGER."</h1>";

		// display main directory
		$this->path();

		Admin::footer();
	}

	/**
	 * Menu
	 *
	 * @return void
	 */
	public function menu()
	{
		if (isset($_GET['root'])) {
			echo "<h1>"._ADMIN_FILEMANAGER."</h1>\n";
			echo "<ul>\n";
			echo "<li><a href='index.php?action=filemanager&amp;page=mkdir&amp;path=".$this->_path."&amp;root=".$this->_root."'>"._ADMIN_FILEMANAGER_MKDIR."</a></li>\n";
			echo "<li><a href='index.php?action=filemanager&amp;page=mkfile&amp;path=".$this->_path."&amp;root=".$this->_root."'>"._ADMIN_FILEMANAGER_MKFILE."</a></li>\n";
			echo "<li><a href='index.php?action=filemanager&amp;page=upload&amp;path=".$this->_path."&amp;root=".$this->_root."'>"._ADMIN_FILEMANAGER_UPLOAD."</a></li>\n";
			echo "</ul>\n";
		}
	}

	/**
	 * Main directory (upload, temporary or skins)
	 *
	 * @var string
	 */
	private $_root;

	/**
	 * Path to files
	 *
	 * @var string
	 */
	private $_dir;

	/**
	 * Path to files
	 *
	 * @var string
	 */
	private $_path;

	/**
	 * Initialize paths to main directory
	 *
	 * @return void
	 */
	private function initDir()
	{
		// set root directory
		switch (_get('root')) {
			case cfg::DIR_TMP:
			case cfg::DIR_SKINS:
			case cfg::DIR_UPLOAD:
				$this->_root = _get('root');
				break;
			default:
				Admin::header(_ADMIN_FILEMANAGER);
				echo "<h1>"._ADMIN_FILEMANAGER."</h1>";
				echo "<ul>\n";
				echo "<li><a href='index.php?action=filemanager&amp;root=".cfg::DIR_TMP."'>".cfg::DIR_TMP."</a> <small>("._ADMIN_FILEMANAGER_DESC_TMP.")</small></li>\n";
				echo "<li><a href='index.php?action=filemanager&amp;root=".cfg::DIR_SKINS."'>".cfg::DIR_SKINS."</a> <small>("._ADMIN_FILEMANAGER_DESC_SKINS.")</small></li>\n";
				echo "<li><a href='index.php?action=filemanager&amp;root=".cfg::DIR_UPLOAD."'>".cfg::DIR_UPLOAD."</a> <small>("._ADMIN_FILEMANAGER_DESC_UPLOAD.")</small></li>\n";
				echo "</ul>\n";
				Admin::footer();
				exit;
		}

		// root directory
		$this->_dir  = dirname(__FILE__).'/../../'.$this->_root;

		// current path
		$this->_path = _hsc(Media::clearPath(urldecode(_get('path'))));
	}

	/**
	 * Display current path
	 *
	 * @return void
	 */
	private function path()
	{
		if (!is_dir($this->_dir.$this->_path)) {
			return print "<p class='red'>"._ADMIN_FILEMANAGER_PATHNOTFOUND."</p>\n";
		}
		
		$scaner = scandir($this->_dir.$this->_path);
		$scaner = array_slice($scaner,2);
		
		echo "<table summary='"._ADMIN_FILEMANAGER."'>\n";
		
		$this->caption();
		
		echo "\t<colgroup valign='middle'>\n";
		echo "\t\t<col width='1%' align='center' />\n";
		echo "\t\t<col width='64%' align='left' />\n";
		echo "\t\t<col width='20%' align='center' />\n";
		echo "\t\t<col width='15%' align='center' />\n";
		echo "\t</colgroup>\n";
	
		echo "\t<thead>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<th>"._ADMIN_FILEMANAGER_TYPE."</th>\n";
		echo "\t\t\t<th>"._ADMIN_FILEMANAGER_FILENAME."</th>\n";
		echo "\t\t\t<th>"._ADMIN_FILEMANAGER_FILESIZE."</th>\n";
		echo "\t\t\t<th>"._ADMIN_ACTIONS."</th>\n";
		echo "\t\t</tr>\n";
		echo "\t</thead>\n";
	
		$this->tfoot();

		// total directories and files
		$total = 0;

		echo "\t<tbody>\n";
		
		if ($this->_dir != $this->_dir.$this->_path) {
			$dotdot = substr(dirname($this->_dir.$this->_path),strlen($this->_dir));
			echo "\t\t<tr>\n";
			echo "\t\t\t<td>".Admin::image('directory_back',_ADMIN_BACK)."</td>\n";
			echo "\t\t\t<td><a href='index.php?action=filemanager&amp;path=".$this->urlencode($dotdot)."/&amp;root=".$this->_root."'>..</a></td>\n";
			echo "\t\t\t<td>&ndash;</td>\n";
			echo "\t\t\t<td>&ndash;</td>\n";
			echo "\t\t</tr>\n";
		}

		// directories
		foreach ($scaner as $key => $filename) {
			if (is_dir($this->_dir.$this->_path.'/'.$filename)) {
				// display name
				$displayname = $filename;

				// convert unreadable characters
				if (extension_loaded('iconv') && stristr($_ENV['OS'],'windows')) {
					$displayname = iconv(mb_detect_encoding($filename),'UTF-8',$filename);
				}

				echo "\t\t<tr>\n";
				echo "\t\t\t<td>".Admin::image('directory','[directory]')."</td>\n";
				echo "\t\t\t<td><a href='index.php?action=filemanager&amp;path=".$this->urlencode($this->_path.'/'.$filename)."/&amp;root=".$this->_root."'>$displayname</a></td>\n";
				echo "\t\t\t<td>&ndash;</td>\n";
				echo "\t\t\t<td>\n";
				echo "\t\t\t\t<a href='index.php?action=filemanager&amp;page=rename&amp;path=".$this->urlencode($this->_path.'/'.$filename)."&amp;root=".$this->_root."'>".Admin::image('rename',_ADMIN_RENAME)."</a>\n";
				echo "\t\t\t\t<a href='index.php?action=filemanager&amp;page=delete&amp;path=".$this->urlencode($this->_path.'/'.$filename)."&amp;root=".$this->_root."'>".Admin::image('delete',_ADMIN_DELETE)."</a>\n";
				echo "\t\t\t</td>\n";
				echo "\t\t</tr>\n";

				// increase number of directories
				$total++;
			}
		}

		// files
		foreach ($scaner as $key => $filename) {
			if (is_file($this->_dir.$this->_path.'/'.$filename)) {
				// display name
				$displayname = $filename;

				// convert unreadable characters
				if (extension_loaded('iconv') && stristr($_ENV['OS'],'windows')) {
					$displayname = iconv(mb_detect_encoding($filename),'UTF-8',$filename);
				}

				// file extension
				$mime = explode('.',$filename);
				$mime = $mime[count($mime)-1];

				// skip templates
				if ('.'.$mime == Main::SKIN_SUFFIX) continue;

				echo "\t\t<tr>\n";
				echo "\t\t\t<td><img src='index.php?action=filemanager&amp;page=icon&amp;mime=$mime' alt='[$mime]' title='[$mime]' /></td>\n";
				echo "\t\t\t<td>$displayname</td>\n";
				echo "\t\t\t<td>".Media::filesize(filesize($this->_dir.$this->_path.'/'.$filename))."</td>\n";
				echo "\t\t\t<td>\n";
				echo "\t\t\t\t<a href='index.php?action=filemanager&amp;page=edit&amp;path=".$this->urlencode($this->_path.'/'.$filename)."&amp;root=".$this->_root."'>".Admin::image('edit',_ADMIN_EDIT)."</a>\n";
				echo "\t\t\t\t<a href='index.php?action=filemanager&amp;page=rename&amp;path=".$this->urlencode($this->_path.'/'.$filename)."&amp;root=".$this->_root."'>".Admin::image('rename',_ADMIN_RENAME)."</a>\n";
				echo "\t\t\t\t<a href='index.php?action=filemanager&amp;page=delete&amp;path=".$this->urlencode($this->_path.'/'.$filename)."&amp;root=".$this->_root."'>".Admin::image('delete',_ADMIN_DELETE)."</a>\n";
				echo "\t\t\t</td>\n";
				echo "\t\t</tr>\n";

				// increase number of files
				$total++;
			}
		}

		// there are no directories and files
		if ($total == 0) {
			echo "\t\t<tr>\n";
			echo "\t\t\t<td colspan='4'>"._ADMIN_FILEMANAGER_EMPTY."</td>\n";
			echo "\t\t</tr>\n";
		}

		echo "\t</tbody>\n";
		
		echo "</table>\n";
	}

	/**
	 * Table heading (shows current opened path)
	 *
	 * @return void
	 */
	private function caption()
	{
		// link to root directory
		$root = false;

		echo "\t<caption>\n";
		echo "\t\t<a href='index.php?action=filemanager'>#</a>\n";
		$nav = explode('/', trim($this->_path,'/'));
		$tmp = NULL;
		foreach ($nav as $key => $value) {
			if ($key > 0) {
				$tmp .= $nav[$key-1]."/";
			}
			if ($tmp.$value."/" == $this->_path || is_file($this->_dir.$tmp.$value)) {
				echo "\t\t".$value;
				if (is_dir(is_file($this->_dir.$tmp.$value))) {
					echo "/";
				}
				echo "\n";
			} else if (is_dir($this->_dir.$tmp.$value)) {
				if (!$root && $this->_path != NULL) {
					echo "\t\t<a href='index.php?action=filemanager&amp;root=".$this->_root."'>/</a>\n";
					$root = true;
				}
				echo "\t\t<a href='index.php?action=filemanager&amp;path=".$tmp.$value."/&amp;root=".$this->_root."'>".$value."/</a>\n";
			} else {
				echo "\t\t$value\n";
			}
		}
		echo "\t</caption>\n";
	}

	/**
	* Table footer
	*
	* @return void
	*/
	private function tfoot()
	{
		/*echo "\t<tfoot>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<td colspan='4' class='left'>\n";
		echo "\t\t\t"._ADMIN_FILEMANAGER."\n";
		echo "\t\t\t</td>\n";
		echo "\t\t</tr>\n";
		echo "\t</tfoot>\n";*/
	}

	/**
	 * Encode URL
	 *
	 * @param string $url
	 * @return string
	 */
	private function urlencode($url)
	{
		$url = explode('/',$url);
		$url = array_map('urlencode',$url);
		return implode('/',$url);
	}

	/**
	 * Edit directory/file
	 *
	 * @return void
	 */
	public function page_edit()
	{
		// initialize path
		$this->initDir();
		$path = $this->_dir.$this->_path;

		Admin::header(_ADMIN_FILEMANAGER);

		echo "<h1>"._ADMIN_FILEMANAGER."</h1>\n";

		if (!is_file($path)) {
			echo "<p><a href='index.php?action=filemanager&amp;path=".dirname($this->_path)."&amp;root=".$this->_root."'>"._ADMIN_FILEMANAGER_BACK."</a></p>\n";
			echo "<p class='red'>"._ADMIN_FILEMANAGER_FILENOTFOUND."</p>\n";
			Admin::footer();
			exit;
		}

		// check if the file is binary or not
		$isBinary = false;
		$handle = fopen($path, 'r');
		fseek($handle, -1, SEEK_END);
		while (!feof($handle)) {
			if (preg_match('/\x00/', fgetc($handle))) {
				$isBinary = true;
			}
		}
		fclose($handle);

		// binary files cannot be modified
		if ($isBinary) {
			$returnPath = dirname($this->_path);
			$returnPath = $returnPath == '.' ? NULL : $returnPath;
			echo "<p><a href='index.php?action=filemanager&amp;path=".$returnPath."&amp;root=".$this->_root."'>"._ADMIN_FILEMANAGER_BACK."</a></p>\n";
			echo "<p class='red'>"._ADMIN_FILEMANAGER_BINARYFILE_ERROR."</p>\n";
			Admin::footer();
			exit;
		}

		if (isset($_POST['submit'])) {
			// file content
			$content = _post('content');

			// write file
			file_put_contents($path, $content);

			// log action
			Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_EDIT,basename($path)));

			Admin::redirect('index.php?action=filemanager&path='.dirname($this->_path).'/&root='.$this->_root);
		}

		echo "<form action='index.php?action=filemanager&amp;page=edit&amp;path=".$this->_path."&amp;root=".$this->_root."' method='post'>\n";
		echo "<fieldset>\n";
		echo "<table>\n";
		
		$this->caption();
		
		echo "\t<thead>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<th colspan='2'>"._ADMIN_FILEMANAGER_FILECONTENT."</th>\n";
		echo "\t\t</tr>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<td class='half'>/".$this->_root.$this->_path."</td>\n";
		echo "\t\t\t<td class='half center'><input name='submit' type='submit' value='"._ADMIN_EDIT."' /></td>\n";
		echo "\t\t</tr>\n";
		echo "\t</thead>\n";
		
		$this->tfoot();
		
		echo "\t<tbody>\n";
		if (is_file($path)) {
			echo "\t\t<tr>\n";
			echo "\t\t\t<td colspan='2'>\n";
			echo "\t\t\t\t<label for='content'>"._ADMIN_FILEMANAGER_FILECONTENT."</label>\n";
			echo "\t\t\t\t<textarea id='content' name='content' rows='25' cols='50'>"._hsc(file_get_contents($path))."</textarea>\n";
			echo "\t\t\t</td>\n";
			echo "\t\t</tr>\n";
		} else {
			echo "\t\t<tr>\n";
			echo "\t\t\t<td>"._ADMIN_FILEMANAGER_FILENOTFOUND."</td>\n";
			echo "\t\t</tr>\n";
		}
		echo "\t</tbody>\n";

		echo "</table>\n";
		echo "</fieldset>\n";
		echo "</form>\n";
		
		Admin::footer();
	}

	/**
	 * Rename directory/file
	 *
	 * @return void
	 */
	public function page_rename()
	{
		// initialize path
		$this->initDir();
		$path = $this->_dir.$this->_path;

		Admin::header(_ADMIN_FILEMANAGER);

		echo "<h1>"._ADMIN_FILEMANAGER_RENAME."</h1>\n";
		echo Element::factory('a', _ADMIN_BACK)->href('index.php?action=filemanager&path='.dirname($this->_path).'/&root='.$this->_root);

		// error reports
		$error = array();

		// return path
		$returnPath = dirname($this->_path);
		$returnPath = preg_match('/^\./', $returnPath) ? NULL : $returnPath;

		if (isset($_POST['submit'])) {
			$filename = Media::clearPath(_post('filename'));
			if (strlen(trim($filename)) < 1 || $filename == '.') {
				$error[] = _ADMIN_FILEMANAGER_FILENAME_ERROR;
			}

			$newPath = substr($path,0,-strlen(basename($this->_path))).$filename;

			// name will not be changed
			if ($path == $newPath) {
				Admin::redirect('index.php?action=filemanager&path='.$returnPath.'/&root='.$this->_root);
			}

			// check if the same directory does not exist
			else if (is_dir($path)) {
				if (is_dir($newPath)) {
					$error[] = _ADMIN_FILEMANAGER_FILE_EXISTS_ERROR;
				}
			}

			// check if the same file does not exist
			else if (is_file($path)) {
				if (is_file($newPath)) {
					$error[] = _ADMIN_FILEMANAGER_DIR_EXISTS_ERROR;
				}
			}

			// there are no errors?
			if (count($error) == 0) {
				if (@rename($path,$newPath)) {
					if (is_dir($newPath)) {
						Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_RENAME_DIR,basename($path),basename($newPath)));
					} else {
						Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_RENAME_FILE,basename($path),basename($newPath)));
					}

					// redirect
					Admin::redirect('index.php?action=filemanager&path='.$returnPath.'/&root='.$this->_root);
				} else {
					echo "<p class='red'>"._ADMIN_FILEMANAGER_RENAME_ERROR."</p>\n";
				}
			} else {
				foreach ($error as $key => $value) {
					echo "<p class='red'>$value</p>\n";
				}
			}
		}

		echo "<form action='index.php?action=filemanager&amp;page=rename&amp;path=".$this->_path."&amp;root=".$this->_root."' method='post'>\n";
		echo "<fieldset>\n";

		echo "<label for='oldname'>"._ADMIN_FILEMANAGER_OLDNAME."</label>\n";
		echo "<input id='oldname' type='text' value='"._hsc(basename($this->_path))."' disabled='disabled' />\n";

		echo "<label for='newname'>"._ADMIN_FILEMANAGER_NEWNAME."</label>\n";
		echo "<input id='newname' name='filename' type='text' value='".(_post('filename') ? _hsc(_post('filename')) : _hsc(basename($this->_path)))."' />\n";

		echo "<p class='center'>\n";
		echo "<input name='submit' type='submit' value='"._ADMIN_RENAME."' />\n";
		echo "</p>\n";

		echo "</fieldset>\n";
		echo "</form>\n";

		Admin::footer();
	}

	/**
	 * Delete directory/file
	 *
	 * @return void
	 */
	public function page_delete()
	{
		// initialize path
		$this->initDir();
		$path = $this->_dir.$this->_path;

		Admin::header(_ADMIN_FILEMANAGER);

		// confirm deletion
		if (_get('sure') == 1) {
			// nadpis
			echo "<h1>"._ADMIN_FILEMANAGER."</h1>\n";

			// set CHMOD to 777
			$old = umask(0);
			chmod($path,0777);
			umask($old);

			// return path
			$returnPath = dirname($this->_path);
			$returnPath = $returnPath == '.' ? NULL : $returnPath;

			// it is a file or directory?
			if (is_file($path)) {
				// delete a file
				if (@unlink($path)) {
					Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_DELETE_FILE,basename($path)));

					Admin::redirect('index.php?action=filemanager&path='.$returnPath.'/&root='.$this->_root);
				} else {
					echo "<a href='javascript:history.go(-2)'>"._ADMIN_BACK."</a>\n";
					echo "<p class='red'>"._ADMIN_FILEMANAGER_DELETEFILE_ERROR."</p>\n";
				}
			} else if (is_dir($path)) {
				// delete a directory
				if (@rmdir($path)) {
					Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_DELETE_DIRECTORY,basename($path)));

					Admin::redirect('index.php?action=filemanager&path='.$returnPath.'/&root='.$this->_root);
				} else {
					echo "<a href='javascript:history.go(-2)'>"._ADMIN_BACK."</a>\n";
					echo "<p class='red'>"._ADMIN_FILEMANAGER_DELETEDIR_ERROR."</p>\n";
				}
			}
		} else {
			Admin::confirm('index.php?action=filemanager&page=delete&path='.$this->_path.'&root='.$this->_root.'&sure=1');
		}

		Admin::footer();
	}

	/**
	 * Create new directory
	 *
	 * @return void
	 */
	public function page_mkdir()
	{
		// initialize path
		$this->initDir();
		$path = $this->_dir.$this->_path;

		Admin::header(_ADMIN_FILEMANAGER_MKDIR);

		echo "<h1>"._ADMIN_FILEMANAGER_MKDIR."</h1>\n";
		echo Element::factory('a', _ADMIN_BACK)->href('index.php?action=filemanager&path='.$this->_path.'&root='.$this->_root);

		// error report
		$error = NULL;

		if (isset($_POST['submit'])) {
			$dirname = _post('dirname');
			if (preg_match('/^([a-zA-Z0-9_-]+)$/',$dirname)) {
				if (!is_dir($path.'/'.$dirname)) {
					if (mkdir($path.'/'.$dirname)) {
						// set chmod to 777
						$old = umask(0);
						chmod($path.'/'.$dirname,0777);
						umask($old);

						Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_MKDIR,$dirname));

						Admin::redirect('index.php?action=filemanager&path='.$this->_path.'&root='.$this->_root);
					} else {
						$error = _ADMIN_FILEMANAGER_MKDIR_ERROR;
					}
				} else {
					$error = _ADMIN_FILEMANAGER_DIR_EXISTS_ERROR;
				}
			} else {
				$error = _ADMIN_FILEMANAGER_MKDIR_NAME_ERROR;
			}
		}

		if ($error !== NULL) {
			echo "<p class='red'>$error</p>";
		}

		echo "<form action='index.php?action=filemanager&amp;page=mkdir&amp;path=".$this->_path."&amp;root=".$this->_root."' method='post'>\n";
		echo "<fieldset>\n";

		echo "<label for='dirname'>"._ADMIN_FILEMANAGER_MKDIR_NAME." <small>(".$this->_path."/)</small></label>\n";
		echo "<input id='dirname' name='dirname' type='text' value='"._hsc(_post('dirname'))."' />\n";

		echo "<p class='center'>\n";
		echo "<input name='submit' type='submit' value='"._ADMIN_ADD."' />\n";
		echo "</p>\n";

		echo "</fieldset>\n";
		echo "</form>\n";

		Admin::footer();
	}

	/**
	 * Create new file
	 *
	 * @return void
	 */
	public function page_mkfile()
	{
		// initialize path
		$this->initDir();
		$path = $this->_dir.$this->_path;

		Admin::header(_ADMIN_FILEMANAGER_MKFILE);

		echo "<h1>"._ADMIN_FILEMANAGER_MKFILE."</h1>\n";
		echo Element::factory('a', _ADMIN_BACK)->href('index.php?action=filemanager&path='.$this->_path.'&root='.$this->_root);

		// error report
		$error = NULL;

		if (isset($_POST['submit'])) {
			$filename = _post('filename');
			if (!strstr($filename,'/')) {
				if (!is_file($path.'/'.$filename)) {
					if (touch($path.'/'.$filename)) {
						// set CHMOD to 777
						$old = umask(0);
						chmod($path.'/'.$filename,0777);
						umask($old);

						Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_MKFILE,$filename));

						Admin::redirect('index.php?action=filemanager&path='.$this->_path.'&root='.$this->_root);
					} else {
						$error = _ADMIN_FILEMANAGER_MKFILE_ERROR;
					}
				} else {
					$error = _ADMIN_FILEMANAGER_FILE_EXISTS_ERROR;
				}
			} else {
				$error = _ADMIN_FILEMANAGER_MKFILE_NAME_ERROR;
			}
		}

		if ($error !== NULL) {
			echo "<p class='red'>$error</p>";
		}

		echo "<form action='index.php?action=filemanager&amp;page=mkfile&amp;path=".$this->_path."&amp;root=".$this->_root."' method='post'>\n";
		echo "<fieldset>\n";

		echo "<label for='filename'>"._ADMIN_FILEMANAGER_MKFILE_NAME." <small>(".$this->_path.")</small></label>\n";
		echo "<input id='filename' name='filename' type='text' value='"._hsc(_post('filename'))."' />\n";

		echo "<p class='center'>\n";
		echo "<input name='submit' type='submit' value='"._ADMIN_ADD."' />\n";
		echo "</p>\n";

		echo "</fieldset>\n";
		echo "</form>\n";

		Admin::footer();
	}

	/**
	 * Upload a new file
	 *
	 * @return void
	 */
	public function page_upload()
	{
		// initialize path
		$this->initDir();
		$path = $this->_dir.$this->_path;

		Admin::header(_ADMIN_FILEMANAGER_UPLOAD);

		echo Element::factory('h1', _ADMIN_FILEMANAGER_UPLOAD);
		echo Element::factory('a', _ADMIN_BACK)->href('index.php?action=filemanager&path='.$this->_path.'&root='.$this->_root);

		if (isset($_FILES['file'])) {
			Media::setRoot($this->_root.$this->_path);

			if (Media::upload($_FILES['file'], '/', $error)) {
				Actionlog::add(sprintf(_LOG_ADMIN_FILEMANAGER_UPLOAD, $_FILES['file']['name']));

				Admin::redirect('index.php?action=filemanager&path='.$this->_path.'&root='.$this->_root);
			} else {
				echo Element::factory('p', $error)->class('red');
			}

			Media::reset();
		}

		$form = Element::factory('form')->action('index.php?action=filemanager&page=upload&path='.$this->_path.'&root='.$this->_root)->method('post')->enctype('multipart/form-data');
		$fieldset = Element::factory('fieldset');

		$fieldset->append('label', _ADMIN_FILEMANAGER_UPLOAD_FILE)->for('file[]');
		$fieldset->append('input')->name('file')->type('file');

		$fieldset->append('p')->class('center')->append('input')->type('submit')->value(_ADMIN_ADD);

		$form->append($fieldset);
		echo $form;

		Admin::footer();
	}

	/**
	 * Create icon regarding to filetype
	 *
	 * @return void
	 */
	public function page_icon()
	{
		// send header
		header('Content-Type:image/png');

		// create PNG image
		$image = imagecreate(16,16);
		$mime  = strtolower(_get('mime'));
		switch ($mime) {
			case 'jpg':
			case 'jpeg':
			case 'png':
			case 'bmp':
			case 'wbmp':
			case 'gif':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAIcSURBVDjLjZO/T1NhFIafc+/trdRaYk1KUEEWjXHRaCSik+E/cDHGzYXB2YHRhMRFY1SYmRgYHZ3VxIRFDYMraMC2hrbQXm7v9+M4UGobiOEk7/adN+9zvnNEVQEQkYvAGBDy/6oBm6rqAVBVeia30jRtGmOctVaPU5qmuri4+AaYAgJVHTKYNsa4drutnU6nr1arpY1GQ6vVqlprdXt7W5eWlvomMv/uw6tSofB4p+NOF0biYtc48tEAhXiuTZzh/s1xyuUyWZbhvWdlZeXt3Nzca14sf6zW6nXf7uzrcfq9s6sLy5+1Xq8fQQKmo1ZCvlAoyo+tXT5tPGO09IckM2zWznH3/AJ3rl5ACInjmGazifceay2VSgWASISSBaz3FIs1RnJlPF18vEG1keDVk1lLFEWICM45wvAfYqTKriqje0lGI01x2qFtuuwkKQ26oEKcCwnDEBFBRA6HfmBw8JWwl3o2ti7j8+u0TUKzcYkrY/n+wyAIEJEjSxEglLyH5r7j+tg8T1oVZr8GzE69JIoiFMiM7zeHYUgQBAMJVBGU77+eYoxhLcvIxnNk6w8xxvDo3hqH+yIieO+HEkQB/qe6bPL5g/cckCkDiBhjOJULhlCGDJIkXX2z+m3GeW4UCnExyxxxHIIOLNLk2WP5AaQXTYDb1tovgHCy8lEUzQS9g1LAO+f2AX+SZudcAjgZOOeJ3jkHJ0zggNpfYEZnU63wHeoAAAAASUVORK5CYII=';
				break;
		
			case 'htm':
			case 'html':
			case 'xhtml':
			case 'xml':
			case 'css':
			case 'js':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJwSURBVDjLjZPdT1JhHMetvyO3/gfLKy+68bLV2qIAq7UyG6IrdRPL5hs2U5FR0MJIAqZlh7BVViI1kkyyiPkCyUtztQYTYbwJE8W+Pc8pjofK1dk+OxfP+X3O83srAVBCIc8eQhmh/B/sJezm4niCsvX19cTm5uZWPp/H3yDnUKvVKr6ELyinwWtra8hkMhzJZBLxeBwrKyusJBwOQ6PRcJJC8K4DJ/dXM04DOswNqNOLybsRo9N6LCy7kUgkEIlEWEE2mwX9iVar/Smhglqd8IREKwya3qhg809gPLgI/XsrOp/IcXVMhqnFSayurv6RElsT6ZCoov5u1fzUVwvcKRdefVuEKRCA3OFHv2MOxtlBdFuaMf/ZhWg0yt4kFAoVCZS3Hd1gkpOwRt9h0LOES3YvamzPcdF7A6rlPrSbpbhP0kmlUmw9YrHYtoDku2T6pEZ/2ICXEQ8kTz+g2TkNceAKKv2nIHachn6qBx1MI5t/Op1mRXzBd31AiRafBp1vZyEcceGCzQ6p24yjEzocGT6LUacS0iExcrkcK6Fsp6AXLRnmFOjyPMIZixPHmAAOGxZQec2OQyo7zpm6cNN6GZ2kK1RAofPAr8GA4oUMrdNNkIw/wPFhDwSjX3Dwlg0CQy96HreiTlcFZsaAjY0NNvh3QUXtHeHcoKMNA7NjqLd8xHmzDzXDRvRO1KHtngTyhzL4SHeooAAnKMxBtUYQbGWa0Dc+AsWzSVy3qkjeItLCFsz4XoNMaRFFAm4SyTXbmQa2YHQSGacR/pAXO+zGFif4JdlHCpShBzstEz+YfJtmt5cnKKWS/1jnAnT1S38AGTynUFUTzJcAAAAASUVORK5CYII=';
				break;
		
			case 'php':
			case 'php3':
			case 'php4':
			case 'php5':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGsSURBVDjLjZNLSwJRFICtFv2AgggS2vQLDFvVpn0Pi4iItm1KItvWJqW1pYsRemyyNILARbZpm0WtrJ0kbmbUlHmr4+t0z60Z7oSSAx935txzvrlPBwA4EPKMEVwE9z+ME/qtOkbgqtVqUqPRaDWbTegE6YdQKBRkJazAjcWapoGu6xayLIMoilAoFKhEEAQIh8OWxCzuQwEmVKtVMAyDtoiqqiBJEhSLRSqoVCqAP+E47keCAvfU5sDQ8MRs/OYNtr1x2PXdwuJShLLljcFlNAW5HA9khLYp0TUhSYMLHm7PLEDS7zyw3ybRqyfg+TyBtwl2sDP1nKWFiUSazFex3tk45sXjL1Aul20CGTs+syVY37igBbwg03eMsfH9gwSsrZ+Doig2QZsdNiZmMkVrKmwc18azHKELyQrOMEHTDJp8HXu1hostG8dY8PiRngdWMEq467ZwbDxwlIR8XrQLcBvn5k9Gpmd8fn/gHlZWT20C/D4k8eTDB3yVFKjX6xSbgD1If8G970Q3QbvbPehAyxL8SibJEdaxo5dikqvS28sInCjp4Tqb4NV3fgPirZ4pD4KS4wAAAABJRU5ErkJggg==';
				break;
		
			case 'txt':
			case 'ini':
			case 'conf':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADoSURBVBgZBcExblNBGAbA2ceegTRBuIKOgiihSZNTcC5LUHAihNJR0kGKCDcYJY6D3/77MdOinTvzAgCw8ysThIvn/VojIyMjIyPP+bS1sUQIV2s95pBDDvmbP/mdkft83tpYguZq5Jh/OeaYh+yzy8hTHvNlaxNNczm+la9OTlar1UdA/+C2A4trRCnD3jS8BB1obq2Gk6GU6QbQAS4BUaYSQAf4bhhKKTFdAzrAOwAxEUAH+KEM01SY3gM6wBsEAQB0gJ+maZoC3gI6iPYaAIBJsiRmHU0AALOeFC3aK2cWAACUXe7+AwO0lc9eTHYTAAAAAElFTkSuQmCC';
				break;
		
			case 'gz':
			case 'tar':
			case 'bz2':
			case 'zip':
			case '7z':
			case 'tgz':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJmSURBVDjLhZNNS5RRGIav8+HMvDNO5ZhOYqXQF2FgVNRCCKM2EbQ1ok2b/AG16F/0ge5qUwitghbWooikiIhI3AQVFER+VsyMztg7vuecp4U2ORH5wLM5cK7n5r65lYg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F5iYVV+FnZTJLB/pN0DDTv7WlHvtuQpLwrYxbv/DfIJt47gQfKZDShFN94TZs+afPW6BGUkecdytqGlX3YPTr7momspN0YAAAAASUVORK5CYII=';
				break;
		
			case 'sql':
			case 's3db':
			case 'db':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHVSURBVDjLjZPLaiJBFIZNHmJWCeQdMuT1Mi/gYlARBRUkao+abHUhmhgU0QHtARVxJ0bxhvfGa07Of5Iu21yYFPyLrqrz1f+f6rIRkQ3icca6ZF39RxesU1VnAVyuVqvJdrvd73Y7+ky8Tk6n87cVYgVcoXixWNByuVSaTqc0Ho+p1+sJpNvtksvlUhCb3W7/cf/w+BSLxfapVIqSySRlMhnSdZ2GwyHN53OaTCbU7/cFYBgG4RCPx/MKub27+1ur1Xqj0YjW6zWxCyloNBqUSCSkYDab0WAw+BBJeqLFtQpvGoFqAlAEaZomuc0ocAQnnU7nALiJ3uh8whgnttttarVaVCgUpCAUCgnQhMAJ+gG3CsDZa7xh1mw2ZbFSqYgwgsGgbDQhcIWeAHSIoP1pcGeNarUqgFKpJMLw+/0q72azkYhmPAWIRmM6AGbXc7kc5fN5AXi9XgWACwAguLEAojrfsVGv1yV/sVikcrksAIfDIYUQHEAoPgLwT3GdzWYNdBfXh3xwApDP5zsqtkoBwuHwaSAQ+OV2u//F43GKRCLEc5ROpwVoOngvBXj7jU/wwZPPX72DT7RXgDfIT27QEgvfKea9c3m9FsA5IN94zqbw9M9fAEuW+zzj8uLvAAAAAElFTkSuQmCC';
				break;
		
			case 'pdf':
				$contentType = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHhSURBVDjLjZPLSx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CC';
		}

		echo base64_decode($contentType);

		imagedestroy($image);
	}
}
